package org.duang.proxy;

import java.lang.reflect.Method;

import org.duang.aop.Proxy;
import org.duang.aop.ProxyChain;
import org.duang.db.sql.DBSession;
import org.duang.ioc.Tx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于SQL数据事务
 * 注： 每一个代理注解只能用于一个方法上，如需要进行多个代理执行操作，可以将service里的method细粒度化
 * @author laotang
 */
public class TxProxy implements Proxy {
	
	private final static Logger logger = LoggerFactory.getLogger(TxProxy.class);
	
	// 判断当前线程是否进行了事务处理，默认为false
	private static final ThreadLocal<Boolean> flagContainer = new ThreadLocal<Boolean>() {
		@Override
		protected Boolean initialValue() {
			return false;
		}
	};
	
	@Override
	public Object doProxy(ProxyChain proxyChain) throws Exception {
		Object resultObj = null;
		Method method = proxyChain.getTargetMethod();
		boolean flag = flagContainer.get();
		// 没有进行事务处理并且是加了Tx注解的方法
		if(!flag && method.isAnnotationPresent(Tx.class)){
			try{
				DBSession.startTransaction();
				resultObj = proxyChain.doProxyChain();
				DBSession.commintTransaction();
			} catch( Exception e ) {
				DBSession.rollbakcTransaction();
				logger.warn(e.getMessage(), e);
				throw e;
			} finally {
				flagContainer.remove();
			}
		}else {
			resultObj = proxyChain.doProxyChain();
		}
		return resultObj;
	}

	public void before() throws Exception {
		
	}
	
	public void after() throws Exception {
	}
}
